package com.mi.easyexceldemo.utils;

import org.apache.commons.collections4.CollectionUtils;
import com.alibaba.fastjson.JSON;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BeanValidator {
    public static <T> void validateValue(Class<T> clazz, String fieldName, Object value) {
        //获得验证器
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        //执行验证
        Set<? extends ConstraintViolation<?>> constraintViolations = validator
                .validateValue(clazz, fieldName, value);
        //如果有验证信息，则取出来包装成异常返回
        if (CollectionUtils.isEmpty(constraintViolations)) {
            return;
        }
        throw new ValidationException(convertErrorMsg(constraintViolations));
    }
    private static String convertErrorMsg(Set<? extends ConstraintViolation<?>> set) {
        Map<String, StringBuilder> errorMap = new HashMap<>();
        String property;
        for (ConstraintViolation<?> cv : set) {
            //这里循环获取错误信息，可以自定义格式
            property = cv.getPropertyPath().toString();
            if (errorMap.get(property) != null) {
                errorMap.get(property).append("," + cv.getMessage());
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(cv.getMessage());
                errorMap.put(property, sb);
            }
        }
        return JSON.toJSONString(errorMap);
    }
}
